package com.qcs.sleep.call;

import android.app.ActivityManager;
import android.content.Context;

import java.util.List;
import java.util.Observable;
import java.util.Observer;

/**
 * Created by chshqiang on 15-7-21.
 * 用于通知所有的 Observer
 */
public class AppChanger extends Observable {
    private static final AppChanger CALL_CHANGER = new AppChanger();

    private long lastSendTime;

    private AppChanger() {
        lastSendTime = 0;
    }

    public static AppChanger getInstance() {
        return CALL_CHANGER;
    }

    public void send(Context context) {
        if (System.currentTimeMillis() - lastSendTime >= 10000) {
            lastSendTime = System.currentTimeMillis();

            ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningTaskInfo> taskInfo = activityManager.getRunningTasks(1);

            if (null != taskInfo) {
                String packageName = taskInfo.get(0).topActivity.getPackageName();
                send(packageName, null, null);
            } else {
                send(null, null, null);
            }
        }
    }

    private void send(String packageName, String appName, String appIcon) {
        AppCaller caller = new AppCaller(packageName, appName, appIcon);

        setChanged();
        notifyObservers(caller);
    }

    @Override
    public void addObserver(Observer observer) {
        if (observer instanceof AppWatcher)
            super.addObserver(observer);
    }

    @Override
    public synchronized void deleteObserver(Observer observer) {
        if (observer instanceof AppWatcher)
            super.deleteObserver(observer);
    }
}
